<template>
  <div
    class="com_container"
    style="position: relative;"
  >
    <div
      class="com_eachrt"
      ref="echart"
    >
    </div>
    <div
      class="left box"
      @click="toLeft"
    >
      <i
        class="el-icon-arrow-left"
        :style="comStyle"
      ></i>
    </div>
    <div
      class="right box"
      @click="toRight"
    >
      <i
        class="el-icon-arrow-right"
        :style="comStyle"
      ></i>
    </div>
    <div
      class="title"
      :style="comStyle"
    >
      {{catName}}
    </div>
  </div>
</template>

<script>
import { getAction } from '@/api/manage';
import '@/assets/echart/theme/chalk';
export default {
  data() {
    return {
      //echartInstance实例类
      chartInstance: null,
      //数据集合
      dataList: null,
      // 当前所展示出的一级分类数据
      currentIndex: 0,
      //标题大小
      titleFontSize: 0,
    };
  },
  mounted() {
    this.initEchart();
    this.getData();
    //设置监听事件，监听窗口大小动态改变echart的大小（注意销毁）
    window.addEventListener('resize', this.screenAdapter);
    // 在页面加载完成的时候, 主动进行屏幕的适配
    this.screenAdapter();
  },
  computed: {
    //当前标题
    catName() {
      if (!this.dataList) {
        return '';
      } else {
        return this.dataList[this.currentIndex].name;
      }
    },
    //左右箭头大小
    comStyle() {
      return {
        fontSize: this.titleFontSize + 'px',
        color: 'gold',
      };
    },
  },
  methods: {
    //初始化echart
    initEchart() {
      //初始化echart对象，并指明主题
      this.chartInstance = this.$echarts.init(this.$refs.echart, 'chalk');
      const initOption = {
        title: {
          text: '▎ 热销商品的占比',
          left: 20,
          top: 20,
        },
        //图例配置
        legend: {
          top: '15%',
          icon: 'circle',
        },
        //鼠标移入扇区，工具提示设置
        tooltip: {
          show: true,
          formatter: (arg) => {
            // console.log(arg)
            const thirdCategory = arg.data.children;
            // 计算出所有三级分类的数值总和
            let total = 0;
            thirdCategory.forEach((item) => {
              total += item.value;
            });
            let retStr = '';
            thirdCategory.forEach((item) => {
              retStr += `
              ${item.name}:${parseInt((item.value / total) * 100) + '%'}
              <br/>
              `;
            });
            return retStr;
          },
        },
        series: [
          {
            type: 'pie',
            label: {
              show: false,
            },
            //鼠标移入扇区，高亮展示设置
            emphasis: {
              //展示标题
              label: {
                show: true,
              },
              //隐藏标题链接线
              labelLine: {
                show: false,
              },
            },
          },
        ],
      };
      this.chartInstance.setOption(initOption);
    },
    //获取服务器数据
    async getData() {
      const { data: resArr } = await getAction('/echart/getJson', {
        fileName: 'hot.json',
      });
      this.dataList = resArr;
      //更新echart
      this.updateChart();
    },
    //更新echart
    updateChart() {
      // 处理图例数据
      const legendData = this.dataList[this.currentIndex].children.map(
        (item) => {
          return item.name;
        }
      );
      //series数据
      const seriesData = this.dataList[this.currentIndex].children.map(
        (item) => {
          return {
            name: item.name,
            value: item.value,
            // 新增加children的原因是为了在tooltip中的formatter的回调函数中,来拿到这个二级分类下的三级分类数据
            children: item.children,
          };
        }
      );
      const dataOption = {
        legend: {
          data: legendData,
        },
        series: [
          {
            data: seriesData,
          },
        ],
      };
      this.chartInstance.setOption(dataOption);
    },
    // 当浏览器的大小发生变化的时候, 会调用的方法, 来完成屏幕的适配
    screenAdapter() {
      // 和分辨率大小相关的配置项
      this.titleFontSize = (this.$refs.echart.offsetWidth / 100) * 3.6;
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: this.titleFontSize,
          },
        },
        legend: {
          itemWidth: this.titleFontSize,
          itemHeight: this.titleFontSize,
          itemGap: this.titleFontSize / 2,
          textStyle: {
            fontSize: this.titleFontSize / 2,
          },
        },
        series: [
          {
            radius: this.titleFontSize * 4.5,
            //设置饼图在中心偏下一点点【第一个是左右，第二个是上下】
            center: ['50%', '60%'],
          },
        ],
      };
      this.chartInstance.setOption(adapterOption);
      // 手动的调用图表对象的resize 才能产生效果
      this.chartInstance.resize();
    },
    toLeft() {
      this.currentIndex--;
      if (this.currentIndex < 0) {
        this.currentIndex = this.dataList.length - 1;
      }
      this.updateChart();
    },
    toRight() {
      this.currentIndex++;
      if (this.currentIndex > this.dataList.length - 1) {
        this.currentIndex = 0;
      }
      this.updateChart();
    },
  },
  destroyed() {
    //销毁监听事件
    window.removeEventListener('resize', this.screenAdapter);
  },
};
</script>

<style lang="scss" scoped>
.left {
  position: absolute;
  top: 0;
  left: 10px;
  width: 100px;
  height: 100%;
  // background-color: red;
  z-index: 10;
  cursor: pointer;
}
.left:hover {
  background-color: rgba($color: #8e8c8c, $alpha: 0.3);
}
.right {
  position: absolute;
  top: 0;
  right: 10px;
  width: 100px;
  height: 100%;
  // background-color: green;
  z-index: 10;
  cursor: pointer;
}
.right:hover {
  background-color: rgba($color: #8e8c8c, $alpha: 0.3);
}
.box {
  display: flex;
  justify-content: center;
  align-items: center;
}
.title {
  position: absolute;
  right: 20%;
  bottom: 15px;
}
</style>